package com.ad.pet.app.account;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.ad.pet.App;
import com.ad.pet.MainActivity;
import com.ad.pet.MainActivityCompent;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.account.adapter.AccountPetAdapter;
import com.ad.pet.app.photo.model.ImageItem;
import com.ad.pet.common.data.utils.FileUtil;
import com.ad.pet.common.data.utils.SpUtil;
import com.ad.pet.common.data.utils.glide.GlideUtil;
import com.ad.pet.common.data.utils.ui.BottomSheetUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.PermissionManager;
import com.ad.pet.common.structure.PhotoManager;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.presenter.photo.PhotoContract;
import com.ad.pet.common.structure.presenter.photo.PhotoPresenter;
import com.ad.pet.common.structure.ui.fragment.LoadingFragment;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.account.Account;
import com.ad.pet.models.remote.account.AccountPet;
import com.ad.pet.models.remote.account.pet.PetCateFirst;
import com.ad.pet.models.remote.account.pet.PetColor;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.just.agentweb.LogUtils;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import rx.functions.Action1;

/**
 * Created by SEELE on 2018/3/22.
 */

public class AccountFragment extends LoadingFragment implements AccountContract.View, PhotoContract.View {

    @BindView(R.id.tv_jifen)
    TextView tvYue;
    @Inject
    RxDisposable mRxDisposable;

    @BindView(R.id.tv_myorder)
    TextView mTvMyOrder;

    @BindView(R.id.dampView)
    ScrollView mDumpScrollView;
    @BindView(R.id.iv_head)
    ImageView mIvHead;
    @BindView(R.id.tv_nick_name)
    TextView mTvNickName;
    @BindView(R.id.relativeLayout_top)
    RelativeLayout mRelatvieLayoutTop;

    @BindView(R.id.tv_reback)
    TextView mTvreBack;

    @BindView(R.id.iv_vip)
    ImageView mIvVip;
    @BindView(R.id.tv_seting)
    TextView mTvSetting;

    @Inject
    AccountPresenter mAccountPresenter;


    @Inject
    FileUtil mFileUtil;

    @BindView(R.id.tv_youhuiquan_number)
    TextView tvYouhuiquanNumber;
    @BindView(R.id.linear_youhui)
    LinearLayout linearYouhui;

    @BindView(R.id.tv_myaddress)
    TextView tvAddress;

    @BindView(R.id.tv_point_number)
    TextView mTvPointNUmber;
    @BindView(R.id.tv_charge)
    TextView mTvCharget;

    @BindView(R.id.tv_collection)
    TextView mTvCollection;
    @BindView(R.id.tv_yuyue)
    TextView mTvYuyue;
    @BindView(R.id.tv_sign)
    TextView mTvSign;
    @BindView(R.id.tv_member)
    TextView mTvMember;

    @BindView(R.id.linear_zuji)
    LinearLayout mLinerPoint;
    @BindView(R.id.recyler_pets)
    RecyclerView mRecyclerPets;

    @BindView(R.id.linear_jifen)
    LinearLayout linear_jifen;


    private File mFile;
    @Inject
    PermissionManager mPermissionManager;

    private BottomSheetDialog mPhotoDialog;
    private View mDialogView;
    private Button mButCancel;
    private Button mButOpen;
    private Button mButPhoto;

    @Inject
    PhotoPresenter mPhotoPresenter;

    AccountPetAdapter accountPetAdapter;
    private Account account;
    private ClipboardManager clipboardManager;

    @Override
    protected void initData() {
//        syncCookie();

//        mAccountPresenter.getUserInfo();
//        mAccountPresenter.getAccountConfig();

        mStatusLayoutManager.showContent();
        accountPetAdapter = new AccountPetAdapter(null);
        mRecyclerPets.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        mRecyclerPets.setAdapter(accountPetAdapter);
        clipboardManager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
    }


    @Override
    protected void initEvents() {

        mTvYuyue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.goMyOrderService(getActivity());
            }
        });
        mRelatvieLayoutTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (account == null)
                    return;
                Navigation.goPersonBaseInfo(getActivity(), account, 111);
            }
        });
//        mIvHead.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                BottomSheetUtil.collapsedDialog(mDialogView);
//                mPhotoDialog.show();
//            }
//        });
        mTvCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.goCollectionSelect(getActivity());
            }
        });
        mButPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
                mRxDisposable.add(mPermissionManager.checkPermissionShowNick(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {
                        Navigation.goPhotoLoaderActivity(mFragment, PhotoManager.REQUEST_CODE_CHECK_IMAGE, 0);
                    }
                }, getString(R.string.storage), Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE));
            }
        });
        mButCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
            }
        });
        //打开相机
        mButOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
                //打开相机
                mRxDisposable.add(mPermissionManager.checkPermissionShowNick(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {
                        mFile = new File(mFileUtil.getRootDir(), System.currentTimeMillis() + ".jpg");
                        //打开相机
                        PhotoManager.openCamera(mFragment, mFile, PhotoManager.REQUEST_CODE_OPEN_CAMERA);
                    }
                }, getString(R.string.camera), Manifest.permission.CAMERA));
            }
        });

        linear_jifen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Navigation.getYueDetail(getActivity());
            }
        });
        mLinerPoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Navigation.goPointDetail(getActivity());
            }
        });

        mTvMyOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.goOrderSeletc(getActivity());
            }
        });

        mTvSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.goHelpCenter(getActivity());
            }
        });
        tvAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.goAddress(getActivity(), null, true, 111);
            }
        });
//        Navigation.goNewUserMall(getActivity(),MainActivity.REQUEST_GO_MALL);

//        mMAccount2Adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                switch (position) {
//                    case 0:
//                        Navigation.goCommonWebView(getActivity(),getString(R.string.help_center),"");
//                        break;
//                    case 1:
//                        break;
//                    case  2:
//                        break;
//                }
//            }
//        });


        mTvreBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.goSuggestFade(getActivity());
            }
        });

        linearYouhui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!hasLogin()){
                    Navigation.goLogin(getActivity(),1,1);
                    return;
                }
                Navigation.goCommonWebView(getActivity(), getString(R.string.conpuons), "/#/mycoupon?token="+ SpUtil.getInstance().getString(Constant.ACCESS_TOKEN), false, MainActivity.REQUEST_GO_MALL);
            }
        });

        accountPetAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Navigation.goPetInfo(getActivity(), accountPetAdapter.getItem(position).getPet_id());
            }
        });

        mTvMember.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.goCommonWebView(getActivity(),"会员升级","/#/vip?token="+SpUtil.getInstance().getString(Constant.ACCESS_TOKEN),false,MainActivity.REQUEST_GO_MALL);
            }
        });

        mTvSign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.goCommonWebView(getActivity(),mTvSign.getText().toString(),"/#/signin?token="+SpUtil.getInstance().getString(Constant.ACCESS_TOKEN)+"&longitude="+ App.longTitu+"&latitude="+App.latitude,false,MainActivity.REQUEST_GO_MALL);
            }
        });

        mTvCharget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (account!=null){
                ClipData mClipData = ClipData.newPlainText("Label",account.getReference_code());
                clipboardManager.setPrimaryClip(mClipData);
                    ToastUtil.getToastUtil().showShort("邀请码已复制！");
            }}
        });
    }

    private void initUMshare() {


//        UMWeb mUMWeb = new UMWeb(mSignCode.getUrl());
//        UMImage mUmImage = new UMImage(getActivity(), R.drawable.ic_share_img);
//        mUMWeb.setThumb(mUmImage);
//        mUMWeb.setTitle(getString(R.string.share_title));
//        mUMWeb.setDescription(getString(R.string.share_desc));
//        new ShareAction(getActivity())
//                .withMedia(mUMWeb)
//                .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ, SHARE_MEDIA.FACEBOOK)
//                .setCallback(new UMShareLinstener()).open(mBoardConfig);

    }


    @Override
    protected void initViews() {
//        mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
//                android.R.color.holo_red_light, android.R.color.holo_orange_light,
//                android.R.color.holo_green_light);

        mAccountPresenter.onCreate(this);
        mPhotoPresenter.onCreate(this);


        mPermissionManager.setRxPermissions(new RxPermissions(getActivity()));
        mDialogView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_dialog_photo, null);
        mButCancel = mDialogView.findViewById(R.id.but_cancel);
        mButPhoto = mDialogView.findViewById(R.id.but_photo);
        mButOpen = mDialogView.findViewById(R.id.but_open);

        mPhotoDialog = new BottomSheetDialog(getActivity());
        mPhotoDialog.setContentView(mDialogView);
        BottomSheetUtil.statusBarTranslucent(mPhotoDialog);


    }

    //7701921958036
    @Override
    public void initInjector() {
        getComponent(MainActivityCompent.class).inject(this);
    }


    @Override
    protected int contentLayout() {
        return R.layout.fragment_account;
    }

    @Override
    protected void clickRetry(View v) {

    }

    @Override
    protected BasePresenter getPresenter() {
        return mAccountPresenter;
    }

    public static AccountFragment newInstance() {
        Bundle args = new Bundle();
        AccountFragment fragment = new AccountFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onDestroy() {

        if (mRxDisposable != null) {
            mRxDisposable.clear();
        }
        super.onDestroy();
    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {
//            mSwipeRefreshLayout.setRefreshing(false);

    }

    @Override
    public void loginOutSuccess() {

    }

    @Override
    public void onResume() {
        super.onResume();
        if (hasLogin()) {
            mAccountPresenter.getUserInfo();

        }

//        mAccountPresenter.getAccountConfig();C6:A6:0B:EF:54:71:15:B5:42:86:7D:0E:57:89:44:46
    }

    @Override
    public void getUserInfoSuccess(Account account) {
        this.account = account;
        if (!TextUtils.isEmpty(account.getUser_headimg())) {
            GlideUtil.loadCircle(mFragment, account.getUser_headimg(), mIvHead);
        }
        mTvNickName.setText(account.getNick_name());
        mTvCharget.setText("点击复制邀请码："+account.getReference_code());
        mTvPointNUmber.setText(account.getPoint() + "");
        tvYouhuiquanNumber.setText(account.getCoupon_num() + "");
        List<AccountPet> list = account.getPet_headimg_list();
        list.add(new AccountPet("-1", ""));
        accountPetAdapter.setNewData(list);
        App.phone=account.getUser_tel();
        App.username=account.getUser_name();
        tvYue.setText(account.getBalance());

        switch (account.getMember_level()) {
            case 1:
                mIvVip.setImageResource(R.drawable.v1);
                break;
            case 2:
                mIvVip.setImageResource(R.drawable.v2);
                break;
            case 3:
                mIvVip.setImageResource(R.drawable.v3);
                break;
            case 4:
                mIvVip.setImageResource(R.drawable.v4);
                break;
        }


//        isHeadAgain = false;
    }

    @Override
    public void getPetInfoSuccess(AccountPet accountPublic) {

    }

    @Override
    public void uploadHead(String user) {

    }


    @Override
    public void upPetInfoSuccesss() {

    }

    @Override
    public void getPetCategorySuccess(List<PetCateFirst> petCateFirst) {

    }

    @Override
    public void getPetColorSuccess(List<PetColor> petColor) {

    }

    @Override
    public void deletePetSuccess() {

    }

    @Override
    public void upPersonInfoSuccess() {

    }


    @Override
    public void error(int code, String msg) {
        LogUtils.e("tag", code + ":" + msg);
//        if (code != 499||code!=402) {
//            ToastUtil.getToastUtil().showShort(msg);
//        }

    }

    @Override
    public void compressComplete(File file) {
        mAccountPresenter.uploadHead(file, "avator");
    }


    @Override
    public void photoCallback(String path) {

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PhotoManager.REQUEST_CODE_CHECK_IMAGE:
                    //选择图片回调 并裁剪
                    ArrayList<ImageItem> path = data.getParcelableArrayListExtra("path");
                    mFile = new File(mFileUtil.getHeaderDir().getPath(), System.currentTimeMillis() + ".jpg");
                    PhotoManager.crop(this, mFile, new File(path.get(0).getImagePath()), PhotoManager.REQUEST_CODE_CROP_CODE);
                    break;
                case PhotoManager.REQUEST_CODE_OPEN_CAMERA:
                    //相机回调
                    PhotoManager.crop(this, mFile, mFile, PhotoManager.REQUEST_CODE_CROP_CODE);
                    break;
                case PhotoManager.REQUEST_CODE_CROP_CODE:
                    //裁剪回调
                    //压缩
                    mPhotoPresenter.compressPhoto(mFile);
                    break;

            }
        }
    }


}
